<template>
  <Container class="role-edit">
    <div class="container-header title title-center" slot="header">
      {{ title }}
      <Button size="large" class="fl btn-back" icon="ios-arrow-back" @click="jumpPrevPage">返回</Button>
    </div>
    <div class="bgs bg-white">
      <div class="content">
        <div class="item">
          <span class="common">业务员手机号:</span>
          <Input v-if="!id" v-model="roleInfo.mobile" class="input" search enter-button placeholder="请输入业务员手机号" @on-search='onSearch' />
          <span v-else>{{roleInfo.mobile}}</span>
        </div>
        <div class="item">
          <span class="common">姓名:</span>
          <span>{{roleInfo.realname}}</span>
        </div>
        <div class="item">
          <span class="common">身份证号码:</span>
          <span>{{roleInfo.idCardNo}}</span>
        </div>
        <div class="item">
          <span class="common">昵称:</span>
          <span>{{roleInfo.nickName}}</span>
        </div>
        <div class="item">
          <span class="common">登录手机:</span>
          <span>{{roleInfo.mobile}}</span>
        </div>
        <div class="item">
          <span class="common">经销商:</span>
          <DistributorSelect v-if="!$route.query.id" :getDataMounted='false' v-model="distributorId"
            ref="distributorSelect" :distributorName="roleInfo.distributorName"
            style="width:200px" :isLabelInvalue="true" @onchange="onSelect" />
          <span v-else>{{roleInfo.distributorName}}</span>
        </div>
        <div class="item">
          <span class="common">品牌:</span>
          <!-- <CheckboxGroup @on-change='onChangeBrand' v-model="checkAllGroup">
            <Checkbox v-for="item in brandList" :key='item.brandId' :label="item.brandId">{{item.brandName}}</Checkbox>
          </CheckboxGroup> -->
          <Checkbox @on-change='onChangeBrand($event, item)' v-for="item in brandList" v-model="item.checked" :key='item.brandId' :label="item.brandId">{{item.brandName}}</Checkbox>
        </div>
        <div class="item">
          <span class="common">职能类型:</span>
          <Select class="select" v-model="roleInfo.roleId">
            <Option v-for="item in roleList" :value="item.id" :key="item.id">{{item.roleName}}</Option>
          </Select>
        </div>
         <div class="item" v-if="$route.query.id">
          <span class="common">审核状态:</span>
          <span>{{ast[roleInfo.auditStatus]}}</span>
        </div>
         <div class="item"  v-if="$route.query.id">
          <span class="common">审核备注:</span>
          <span>{{roleInfo.auditMemo}}</span>
        </div>
        <div class="item">
          <span class="common">选择门店:</span>
         
        </div>
        <div class="tab-container" v-if="$route.path === '/setting/dealers/edit'">
          <Department
            v-if="mounted"
            ref="department"
           :salesmanId='roleInfo.salesmanId'
           :brandIds='checkAllGroup' 
           :distributorId='distributorId'
           :form="form"/>
        </div>
      </div>
    </div>
    <Loader :status="status" @refresh="getInfo"></Loader>
    <div class="container-footer bg-white" slot="footer">
      <div>
        <Button type="primary" class="mr" size="large" :disabled="isDisabled" @click="onSave">保存</Button>
        <Button type="primary" class="mr" size="large" @click="jumpPrevPage">取消</Button>
      </div>
    </div>
  </Container>
</template>
<script>
import Department from "./edit/Department";
import SelectList from '@/components/SelectList';
import DistributorSelect from '~/DistributorSelect';

export default {
  components: {
    Department,
    SelectList,
    DistributorSelect
  },
  data() {
    return {
      id: null,
      title: "签约业务员",
      status: 'pass',
      ast: { 0: "待审核" , 1: "审核不通过", 2: "审核通过"},
      rules: {
        name: [{ required: true, message: "不能为空", trigger: "blur" }]
      },
      tab: "tab1",
      form: {
        name: ""
      },
      brandList: [],
      checkAllGroup: [],
      distributorId: '', // 选择的经销商
      roleList: [], // 角色列表
      departmentTree: [], // 业务部门树
      departmentId: '',
      mounted: false,
      roleInfo: { salesmanContractBrandDTOS: [],roleId:'', mobile:'', email:'', auditStatus:'', realname:'', nickName:'' }, // 业务员信息
    };
  },
  computed: {
    roleitem() {// 选中的角色
      return this.roleList.find(item => item.id == this.roleInfo.roleId) || {}
    },
  },
  created() {
    this.id = this.$route.query.id
    this.getBaseSignInfo()
    this.getDptRoles()
  },
  mounted() {
    this.mounted = true
  },
  methods: {
    onChangeBrand(val, item) {
      let selected = this.$refs.department.hasListWithSelect.find(i => i.brandId === item.brandId)
      if (this.$route.query.id && !val && selected) { // 有路由id且已选择门店在取消选择的时候
        this.$Modal.confirm({
            title: '提示',
            content: '该品牌已有已选门店，是否确认取消?确认后，该品牌的门店签约数据保存后将从已选门店中删除',
            onOk: () => {
              this.getCheckedBrandId()
            },
            onCancel: () => {
              item.checked = true
            }
        });
      } else {
        this.getCheckedBrandId()
      }
    },
    getBaseSignInfo() {
      if(!this.id) return
      this.status = 'loading'
      this.$ajaxGet('/distributor_salesman/contractInfo', { contractId: this.id }).then(res => {
        this.status = 'pass'
        this.distributorId = res.distributorId
        this.roleInfo = Object.assign(this.roleInfo, res)
        // this.$refs.distributorSelect.selectDefault(this.roleInfo.distributorName)
        this.getDistributorSelectInfo()
        this.getSignedStore(res)
      })
    },
    getDistributorSelectInfo() {
        let param = {
          distributorId: this.roleInfo.distributorId,
        }
        return this.$ajaxGet("/distributor/contract/pageSignedDistributor", param).then(data => {
           let item = data.records[0] || {}
           this.onSelect({ value: item.distributorId,label: item.distributorName })
        })
    },
    onSelect(val = {}) {
      this.distributorId = val && val.value
      this.roleInfo.distributorId = val.value
      this.roleInfo.distributorName = val.label
      this.getSignedInfo().then(() => {
        if (val && val.value) {
          this.$ajaxGet('/distributor_salesman/listBrands', { distributorId: val.value }).then(res => {
            // this.brandList = res
            if (!this.$route.query.id) { // 默认全选
              this.brandList = res.map(item => {
                item.checked = true
                return item
              })
            } else {
              this.brandList = res.map(item => {
                if (this.roleInfo.salesmanContractBrandDTOS.find(i => i.brandId === item.brandId)) {
                  item.checked = true
                } else {
                  item.checked = false
                }
                return item
              })
            }
            this.getCheckedBrandId()
          })
        } else {
          this.brandList = []
          this.getCheckedBrandId()
        }
      })
    },
    getCheckedBrandId() {
      if (!this.brandList.length) {
        this.checkAllGroup = []
        return
      }
      this.checkAllGroup = this.brandList.filter(item => item.checked).map(item => item.brandId)
    },
    onSearch(val) {
      this.$jsonPost('/distributor_salesman/mobile/exists', { mobile: val }).then(res => {
        let { id: salesmanId, mobile, email, auditStatus, realname, nickName } = res
        this.roleInfo.salesmanId = salesmanId
        this.roleInfo.mobile = mobile
        this.roleInfo.auditStatus = auditStatus
        this.roleInfo.realname = realname
        this.roleInfo.nickName = nickName
        this.getSignedInfo()
      })
    },
    getDptRoles() {
      this.$ajaxGet('/distributor_salesman/findRoles').then(res => {
        this.roleList = res
      })
    },
    getSignedInfo () {
      return new Promise((resolve, reject) => {
        if (this.$route.query.id) { // 编辑状态
          resolve()
          return
        }
        let salesmanId = this.roleInfo.salesmanId
        let distributorId = this.distributorId
        if (!distributorId || !salesmanId) {
          this.id = ''
          this.roleInfo.salesmanContractBrandDTOS = []
          this.$refs.department.clearSignedDistributor()
          resolve()
          return
        }
        this.$ajaxGet('/distributor_salesman/contractByDistributorId', { salesmanId, distributorId }).then(res => {
          let item = (res || []).find(item => item.distributorId === distributorId)
          if (item) {
            this.id = item.id
            this.roleInfo.salesmanContractBrandDTOS = item.salesmanContractBrandDTOS
            this.roleInfo.salesmanId = item.salesmanId
            this.roleInfo.roleId = item.roleId
            this.getSignedStore(item)
          } else {
            this.id = ''
          }
          resolve()
        })
      })
      
    },
    getSignedStore(res) {
      if (res.salesmanContractBrandDTOS.length === 0) return // 没有签约品牌可能处于解约状态，不请求签约门店数据
          let p = {
            distributorId: res.distributorId,
            masterBrandIds: res.salesmanContractBrandDTOS.map(i => i.brandId),
            salesmanId: res.salesmanId
          }
          this.$refs.department.getSignedDistributor(p)
    },
    jumpPrevPage() {
      this.$router.back();
    },
    onSave() {
      if (!this.roleInfo.salesmanId) {
        this.$Message.warning('请根据手机号获取业务员信息')
        return
      }
      if (!this.roleInfo.distributorName) {
        this.$Message.warning('请选择经销商')
        return
      }
      if (!this.checkAllGroup.length) {
        this.$Message.warning('请选择品牌')
        return
      }
      if (!this.roleInfo.roleId) {
        this.$Message.warning('请选择职能类型')
        return
      }
      let list = this.$refs.department.changeList.filter(e => e.checked).map(item => item.id)
      let unsignList = this.$refs.department.hasList.filter(e => e.unsign).map(item => item.id)
      let params = {
        storeDisContractIds: unsignList,
        salesmanContractDTOs: [
          {
            id: this.id,
            distributorId: this.roleInfo.distributorId,
            distributorName: this.roleInfo.distributorName,
            realname: this.roleInfo.realname,
            roleId: this.roleitem.id,
            roleName: this.roleitem.roleName,
            salesmanId: this.roleInfo.salesmanId,
            salesmanContractBrandDTOS: this.checkAllGroup.map(item => {
              let bi = this.brandList.find(b => b.brandId == item)
              return {
                brandId: bi.brandId,
                brandName: bi.brandName
              }
            }),
          }
        ],
        storeContractIds: list
      }
      let url = '/distributor_salesman/contract'
      this.$jsonPost(url, params).then(res => {
        this.$Message.success('操作成功')
        this.jumpPrevPage()
      })
    }
  }
};
</script>

